package com.example.demo.filters;

import com.example.demo.domain.ResultMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * 校验是否存在指定的请求头
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求路径
        System.err.println(String.format("全局过滤器获取到请求路径：%s", exchange.getRequest().getURI()));
        String test = exchange.getRequest().getHeaders().getFirst("test");
        // 无test请求头
        if (!Optional.ofNullable(test).isPresent()) {
            System.err.println("无指定请求头");

            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
            ResultMessage result = new ResultMessage(false, "无指定请求头");
            String body = toJson(result);
            DataBuffer dataBuffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }
        System.err.println(String.format("请求头参数:%s", test));
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private String toJson(ResultMessage result) {
        ObjectMapper mapper = new ObjectMapper();
        String body = null;
        try {
            body = mapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return body;
    }
}
